package com.cn.codebrush.字符串;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Boolean
 * @Date 2022/6/12 16:35
 * @Version 1.0
 */
public class No890查找和替换模式 {
    public static void main(String[] args) {
        String[] words = {"abc","deq","mee","aqq","dkd","ccc"};
        String[] words1 = {"ccc","abc","mee"};
        String pattern = "abb";
        System.out.println(findAndReplacePattern(words1,pattern));
    }


    /**
     * 解法二  构造双映射
     * @param words
     * @param pattern
     * @return
     */
    public static List<String> findAndReplacePattern(String[] words, String pattern) {
        List<String> list = new ArrayList<>();
        for(String word:words){
            if(findAndReplacePatternHelper(word,pattern) && findAndReplacePatternHelper(pattern,word)){
                list.add(word);
            }
        }
        return list;
    }

    public static boolean findAndReplacePatternHelper(String word, String pattern) {
        Map<Character,Character> map = new HashMap<>();
        for(int i=0;i<pattern.length();i++){
            char x = word.charAt(i);
            char y = pattern.charAt(i);
            if(!map.containsKey(x)){
                map.put(x,y);
            }else if(map.get(x) != y){
                return false;
            }
        }
        return true;
    }






    /**
     * 解法一
     * @param words
     * @param pattern
     * @return
     */
    public static List<String> findAndReplacePattern1(String[] words, String pattern) {
        List<String> list = new ArrayList<>();
        int n = pattern.length();
        int[] nums = new int[n];
        for(int i=0;i<n;i++){
            nums[i] = i;
            for(int j=0;j<=i;j++){
                if(pattern.charAt(j) == pattern.charAt(i)){
                    nums[i] = j;
                    break;
                }
            }
        }

        for(int p=0;p<words.length;p++){
            int[] tempNums = new int[n];
            list.add(words[p]);
            for(int i=0;i<n;i++){
                tempNums[i] = i;
                for(int j=0;j<=i;j++){
                    if(words[p].charAt(j) == words[p].charAt(i)){
                        tempNums[i] = j;
                        break;
                    }
                }

                if(tempNums[i] != nums[i]){
                    list.remove(list.size()-1);
                    break;
                }

            }
        }

        return list;

    }
}
